package com.user.controller;

import com.express.entity.Result;
import com.express.entity.StatusCode;
import com.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import pojo.User;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 查询全部用户的数据
     *
     * @return
     */
    @GetMapping("/findAll")
    public Result<User> findAll() {
        List<User> userList = userService.finAll();
        return new Result<>(true, StatusCode.OK, "查询成功", userList);
    }

    /**
     * 根据用户的id来查询用户的全部信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/findById/{userId}")
    public Result<User> findUserById(@PathVariable("userId") Integer userId) {
        User user = userService.findUserById(userId);
        return new Result<>(true, StatusCode.OK, "查询成功", user);
    }

    /**
     * 通过用户的id查询用户的手机号
     *
     * @param userId
     * @return
     */
    @GetMapping("/findById/{userId}")
    public Result findPhoneNumberById(@PathVariable("userId") Integer userId) {
        Integer telephoneNumber = userService.findPhoneNumberById(userId);
        return new Result<>(true, StatusCode.OK, "查询成功", telephoneNumber);
    }

    /**
     * 添加一个新的用户信息
     *
     * @param user
     * @return
     */
    @Transactional
    @PostMapping("/add")
    public Result addUser(@RequestBody User user) {
        userService.addUser(user);
        return new Result<>(true, StatusCode.OK, "添加成功");
    }

    /**
     * 修改用户的信息
     * @param user
     * @param userId
     * @return
     */
    @Transactional
    @PutMapping("/update/{userId}")
    public Result update(@RequestBody User user, @PathVariable("userId") Integer userId) {
        user.setUserId(userId);
        userService.update(user);
        return new Result<>(true, StatusCode.OK, "修改成功");
    }

    /**
     * 通过传来的用户id来删除一个用户的信息
     *
     * @param userId
     * @return
     */
    @Transactional
    @DeleteMapping("/deleteById/{userId}")
    public Result deleteById(@PathVariable("userId") Integer userId) {
        userService.deleteById(userId);
        return new Result<>(true, StatusCode.OK, "删除成功");
    }
}
